﻿using System.Collections.Generic;
using Framework;

namespace Game
{
    public class CommonEntity : EventTarget, IDisposable
    {
        protected List<IComponent> _componentList = new List<IComponent>();
        private List<IComponent> _sharedComponentList = new List<IComponent>();

        public T AddComponent<T>() where T : IComponent, new()
        {
            T component = new T();
            _componentList.Add(component);
            return component;
        }

        public void AddSharedComponent(IComponent component)
        {
            _sharedComponentList.Add(component);
        }
        
        public T RemoveComponent<T>() where T : IComponent
        {
            T component = GetComponent<T>();
            if (component != null)
            {
                _componentList.Remove(component);
            }
            return component;
        }
        
        public void RemoveSharedComponent(IComponent component)
        {
            _sharedComponentList.Remove(component);
        }

        public T GetComponent<T>() where T : IComponent
        {
            for (int i = 0; i < _componentList.Count; ++i)
            {
                if (_componentList[i].GetType() == typeof(T))
                {
                    return (T)_componentList[i];
                }
            }

            for (int i = 0; i < _sharedComponentList.Count; ++i)
            {
                if (_sharedComponentList[i].GetType() == typeof(T))
                {
                    return (T) _sharedComponentList[i];
                }
            }
            return default;
        }

        public virtual void Dispose()
        {
            for (int i = 0; i < _componentList.Count; ++i)
            {
                _componentList[i].Dispose();
            }

            _componentList = null;
            _sharedComponentList = null;
        }
    }
}